#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月16日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

sys.path.append('../')
from base.localConfig import baseLocalConfig


hiveHost = baseLocalConfig.hiveConfig['host']
hivePort = baseLocalConfig.hiveConfig['port']
hiveUser = baseLocalConfig.hiveConfig['user']
hivePasswd = baseLocalConfig.hiveConfig['passwd']
hiveAuthMechanism = baseLocalConfig.hiveConfig['authmechanism']
hiveDB = baseLocalConfig.hiveConfig['db']
hiveTab = baseLocalConfig.hiveConfig['tab']
from hiveServer2 import HiveClient2

import logging

class ZhimindHiveDatas():
    def __init__(self,host='localhost',port=10002,user='root',passwd='',db='default',authMechanism="PLAIN",tab='newhivehistoryrole'):
        self.myHiveClient = HiveClient2(host=host,port=port,user=user,passwd=passwd,db=db,authMechanism=authMechanism)
        self.tab = tab
    
    def conv_list_to_str(self,alist):
        
        blist = []
        for a in alist:
            blist.append("%s"%a)
        
        return '"'+'","'.join(blist)+'"'
    
    def get_customer_cnt(self,tab='newhivehistoryrole',groups=[],startTime=None,endTime=None):
        return self.get_customer_cnt_by_dur(tab=tab, groups=groups, startTime=startTime, endTime=endTime, minDur=None, maxDur=None)
    
    def get_customer_cnt_by_dur(self,tab='newhivehistoryrole',groups=[],startTime=None,endTime=None,minDur=0,maxDur=24*60*60*1000):
        datas = {}
        query = 'select grp,count(*) from %s where role in (3,10)'%tab
        if len(groups)==0:
            pass
        elif len(groups)==1:
            query = query + ' and grp="%s"'%groups[0]
        else:
            query = query + ' and grp in (%s)'%(self.conv_list_to_str(groups))
        
        if startTime!=None and  endTime!=None:
            query = query + ' and day between "%s" and "%s"'%(startTime,endTime)
        if minDur!=None and maxDur!=None:
            query = query + ' and dur between "%s" and "%s"'%(minDur,maxDur)
        query = query + ' group by grp'
        logging.debug(query)
        rets = self.myHiveClient.selectAll(query)
        if rets==None:rets=[]
        for ret in rets:
            retList = ret.split('\t')
            if len(retList)!=2:continue
            group,count = retList
            datas[int(group)] = int(count)
        logging.info('Found %s Records.'%len(datas))
        for group in groups:
            if not datas.has_key(int(group)):
                datas[int(group)] = '-'
        
        return datas
    
    
    
    def get_flow(self,st=None,et=None,role=None,distinct=True):
        if distinct == True:
            query = 'select count(distinct mac) '
        else:
            query = 'select count(mac)'
        query += ' from %s'%(self.tab)
        
        query_where_list = []
        if st!=None and et==None:
            query_where_list.append( ' day>="%s" '%st)
        elif st==None and et!=None:
            query_where_list.append( ' day <="%s" '%et)
        elif st !=None and et !=None:
            query_where_list.append( ' day between "%s" and "%s" '%(st,et))
        
        if role==3 or role==10:
            query_where_list.append( '  role in (3,10) ')
        elif role == 1 or role == -1:
            query_where_list.append(' and role in (1,-1) ')
        elif role == 0:
            query_where_list.append( ' and role!=2 ')
        elif role == 2:
            query_where_list.append(' and role=2 ')
        
        if len(query_where_list)!=0:
            query +=' where %s '%(' and '.join(query_where_list))
            
        logging.debug(query)
        ret = self.myHiveClient.SelectOne(query)
        count =ret[0]
        return count
    
    def get_flow_by_group_and_type(self,day,role=0,distinct=True):
        if distinct == True:
            query = 'select grp,count(distinct mac) '
        else:
            query = 'select grp,count(mac)'
        query += ' from %s where day="%s" '%(self.tab,day)
        if role==3 or role==10:
            query += ' and role in (3,10)'
        elif role == 1 or role == -1:
            query += ' and role in (1,-1)'
        elif role == 0:
            query += ' and role!=2'
        elif role == 2:
            query += ' and role=2'
        else:
            pass
        query += ' group by grp'
        print query
        logging.debug(query)
        rets = self.myHiveClient.SelectAll(query)
        datas = {}
        for group,count in rets:
            datas[int(group)] = int(count)
        return datas
    
    
myZhimindHiveDatas = ZhimindHiveDatas(host=hiveHost,port=hivePort,user=hiveUser,passwd=hivePasswd,db=hiveDB,authMechanism=hiveAuthMechanism,tab=hiveTab)       
if __name__=='__main__':
    print myZhimindHiveDatas.get_flow_by_group_and_type(day='2015-01-02')
        